[Android] Building a Menu for your Android (V1.0 R1) App

In Building a simple menu in Android, a menu was built using the MenuBuilder. Since the release of version 1.0 (release 1), MenuBuilder has been removed. In this tutorial, we’ll set up a custom menu that gets displayed when the menu button is pressed.

To add the menu for your application, your activity needs to override the onCreateOptionsMenu method. The method will be given the instance of the menu to popuplate. Our overridden method will add the items to the instance that is given. To control what happens when an item on the menu is selected, override the onOptionsItemSelected method. Here is the first part of the code that sets up the activity and adds a couple of items to our menu:


 1 package com.android.menu;
 2
 3 import android.app.Activity;
 4 import android.app.AlertDialog;
 5 import android.os.Bundle;
 6 import android.view.Menu;
 7 import android.view.MenuInflater;
 8 import android.view.MenuItem;
 9 import android.view.SubMenu;
10
11 public class MenuDemo extends Activity
12 {
13   /** 
14    * Called when the activity is first created. 
15    */
16   @Override
17   public void onCreate(Bundle savedInstanceState) 
18   {
19     super.onCreate(savedInstanceState);
20     setContentView(R.layout.main);      
21   }
22     
23   /**
24    * {@inheritDoc}
25    */
26   @Override
27   public boolean onCreateOptionsMenu(Menu menu) 
28   {
29     super.onCreateOptionsMenu(menu);
30     
31     MenuItem item = menu.add("Painting");
32     item.setIcon(R.drawable.paint);
33     
34     item = menu.add("Photos");
35     item.setIcon(R.drawable.photos);
36     

The call to to the setIcon method attachs an image to the menu item. In the example above, the images have been placed in the appropriate resources directory and is being referenced from there.

The items added so far are top level items. Now let’s say we want to attach a submenu. This is as easy as calling the addSubMenu method.


37     SubMenu subScience = menu.addSubMenu(
38         R.string.scienceMenuName);
39     subScience.setIcon(R.drawable.science);
40

To add items to our submenu, we can create the menu items programatically (like we did with the top level menu). However, just to show you another way of setting up the menu, we’ll use load up a menu specified by a menu XML file here instead. You can use the Android Menu Editor to edit the XML if you want (in Eclipse, create an XML file and then right click on the file Open With -> Android Menu Editor) or you can use the text editor to manually create the XML. Below is the contents of the XML file that I used:


1 <menu xmlns:android="http://schemas.android.com/apk/res/android">
2   <item android:title="Physics" />
3   <item android:title="Chemistry" />
4   <item android:title="Biology" />
5 </menu>
6

It should be noted that we could have also created our top level menu the same way! The loading of the menu from an XML file is done through the use of a MenuInflater.


41     // Now, inflate our submenu.
42     MenuInflater inflater = new MenuInflater(this);
43     inflater.inflate(R.menu.menu, subScience);
44

Of course, once the menu has been loaded from an XML file, we can still add items to the submenu.


45     // Programatically, add one item to the submenu.
46     subScience.add("Meteorology");
47

To make the menu displayable when the menu button is pressed, the method needs to return true.


48     // Return true so that the menu gets displayed.
49     return true;
50   }
51

With the menu setup, we now override the onOptionsItemSelected method to handle menu selections. The selected menu item is given back as the method parameter. In this example, the an alert dialog simply pops up, showing what item was selected.


52   /**
53    * {@inheritDoc}
54    */
55   public boolean onOptionsItemSelected(MenuItem item)
56   {
57
58     if (item.hasSubMenu() == false)
59     {
60       // For this demo, lets just give back what
61       // we found.
62       AlertDialog.Builder dialogBuilder = new 
63         AlertDialog.Builder(this);
64   
65       dialogBuilder.setMessage(" You selected " +
66           item.getTitle());
67   
68       dialogBuilder.setCancelable(true);
69       dialogBuilder.create().show();
70     }
71     
72     // Consume the selection event.
73     return true;
74   }
75 }
76

33 Responses to [Android] Building a Menu for your Android (V1.0 R1) App

  1. Pingback: Building a simple menu in Android « Kah - The Developer

  2. Colin Dean says:

    Excellent little tutorial, mate. Android really has a neat SDK!

  3. Pingback: [Android] Defining a Context Menu for your View « Kah - The Developer

  4. Ravisankar S says:

    Hi,
    I tried to create an Menu bar in Android Project but in code I am facing some queries like “How do design the class and xml file for this”. Please help for this.
    Thanks a lot…
    Regards,
    Ravisankar S
    +91 988 477 9432

    • kahgoh says:

      I don’t really understand what you are asking or what you are after. Once you have figured out how you want your menu to look, you should be able to easily translate it to code or the XML file. Also, note that the code in this little tutorial may also be out of date, as they have release later versions of the SDK.

  5. Pingback: KamoBagula.com » Blog Archive » How to build menus in Android

  6. sam says:

    i want to open up options menu when a custom button is clicked … is it possible? if so, please help me out

    thanks in advance

  7. vipul says:

    Hi..
    How to create the permenent menus??.. I want the menu stays visible to user..I don’t want him to press the menu key each time..

    Is it possible to develop such menu??? if yes..I would appriciate your help

    • kahgoh says:

      I can’t really figure out how to do this either from the current API. I’m not even sure why you would want to keep the option menu opened permenantly. If you really do need to keep something like the options menu open “permenently”, you could probably use a panel with buttons that stays open. However, if you really do feel you need to keep it open, I guess you try asking over at StackOverflow.

  8. vipul says:

    Thank you very much for your prompt reply.

    Basically in my application there are lot of activities and each actvities may have (different or same menu)options user can select.

    There may be some activities which may not require menu at all.

    So I just don’t want user to keep guessing and press the menu key to look for options he may have from current activity.

    I like your suggestion of having panel with multiple buttons.
    So for example my three activities require same menu (panel with buttons)…
    in that case, can we have something like master detail activity.
    Master Activity(Contains my menu) stays visible during all
    my Child Activities(Contains other UI stuff) executing.

    Fundamentally i know at a time only one activity should run, but is there any other way you think of achiving this scenario.

    Please let me know if, i am not able to make you understand.

    Thanks

    • kahgoh says:

      To me, it should be fairly obvious which items or “options” should (and should NOT) be available in an activity’s options menu. So it should be fairly intuitive and easy for the user to “guess” what items are in the options menu based on what is on the screen. Basically, I don’t even think that you should try to keep it open in any of the activities!

      Besides, menus in mose other application will normally close if an item is selected or something outside the menu is pressed. Changing the menu to stay open, even after an item is selected, is something that could be unintuitive (since it isn’t the usual behaviour) and just take up precious screen space.

      If you really need a menu that stays open, then I think should consider using a toolbar or menubar instead. This could easily be done using a “panel with buttons”. The only difference is that toolbars and menubars don’t need to be “opened” by pressing the MENU button.

      • vipul says:

        Thanks again….

        Actually we already have the iphone version of the app, which i am going to build. And if you know iphone
        do not have menu key. So we do have Menubars on top of the app. And we are planning to have
        identical design.

        Anyways, your inputs are very helpful and we will probably go for panel with buttons.

  9. spiker says:

    My application crashes when started…..!

    ////////////java_file/////////////////////TestCal.java////////////////////
    package simplecalc.calc;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.SubMenu;
    
    public class TestCal extends Activity
    {
     /** 
      * Called when the activity is first created. 
      */
     @Override
    public void onCreate(Bundle savedInstanceState) 
     {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);      
     }
       
     /**
      * {@inheritDoc}
      */
     @Override
     public boolean onCreateOptionsMenu(Menu menu) 
     {
       super.onCreateOptionsMenu(menu);
       
       MenuItem item = menu.add("Painting");
       item.setIcon(R.drawable.icon);
       
       item = menu.add("Photos");
       item.setIcon(R.drawable.icon);
    
       SubMenu subScience = menu.addSubMenu(
           R.string.scienceMenuName);
       subScience.setIcon(R.drawable.icon);
       // Now, inflate our submenu.
       MenuInflater inflater = new MenuInflater(this);
       //inflater.inflate(R.menu.menu, subScience);
     // Programatically, add one item to the submenu.
       subScience.add("Meteorology");
    //Return true so that the menu gets displayed.
       return true;
     }
    /**
      * {@inheritDoc}
      */
     public boolean onOptionsItemSelected(MenuItem item)
     {
    
       if (item.hasSubMenu() == false)
       {
         // For this demo, lets just give back what
         // we found.
         AlertDialog.Builder dialogBuilder = new 
           AlertDialog.Builder(this);
     
         dialogBuilder.setMessage(" You selected " + item.getTitle());
     
         dialogBuilder.setCancelable(true);
         dialogBuilder.create().show();
       }
       
       // Consume the selection event.
       return true;
     }
    }
    
    ////////////////////end of file/////////////////
    
  10. spiker says:

    ///////////main.xml////////////////////

    /////////////////end of file//////////////////
    /////////////////strings.xml////////////////

    Hello World, TestCalc!
    Simple Calculator

    ////////////////end of file//////////////////

    ///////////////AndroidPeaseed Manifest//////////////////

    /////////////////////end of file/////////////////

    please help me….!

    • spiker says:

      xml not displaying….?

      • kahgoh says:

        I suspect XML is not displaying because of the tags. Try putting [sourcecode language="xml"] at top of your xml and [/sourcecode] at the bottom. I used this same tag to format your code above. If you are working in Eclipse you would probably see an exception in the LogCat view (open the DDMS perspective or go through Window -> Show View -> Other… -> Android -> LogCat). If there is an exception and a stack trace, it would be useful to know.

        Tip:
        I noticed that you are following the example that I wrote a very long time ago, where the dialog is created each time it needs to be shown (when a certain item has been selected). Having to create the same dialog each time is rather inefficient. The only thing that changes is text that displays what has been selected. I think the application would be faster if showDialog(int) was used instead. If you take this approach, you will need to override onCreateDialog instead. The method onOptionsItemSelected then just needs to update the dialog and call showDialog(int).

  11. spiker says:

    //////////////////AndroidPeaseed Manifest//////////////


    ///////////////////end of file/////////////////

  12. Venkatraman says:

    I am having a list of names in my resources and when I tap and hold any items on that list I need to change its font style using menu help me on this issue. please send me some sample code since I am new to this technology

  13. Munirasu says:

    Hi Kahgoh,

    Newly i created database in android its working fine, but i need to synchronize all the contacts from mobile to database, for that i need to create menu options,,,, so could u plz suggest me..?

    Regards
    Munirasu

    • kahgoh says:

      Hi,

      I don’t understand what you are asking for. Could you provide information on what you are trying to achieve and also what have you tried? Did you just want to create a menu item for synchronizing the contacts database?

  14. Aditya says:

    Icon is not coming….
    Help..

    • kahgoh says:

      Hi,

      You will need to add your own icons to the project first. You should place them in one of subdirectories under res. The subdirectories under res (drawable-hdpi, drawable-mdpi and drawable-ldpi) allow you to provide different versions of the icon, depending on the screen resolution of the device (see documentation on Supporting Multiple Screens). Then, in your code, you can reference these resources to use them as the icons.

  15. Clinton says:

    Hi there, i have a problem in the following line:

    inflater.inflate(R.menu.menu, subScience);

    eclipse does not find R.menu. Please can you tell me what is my prob? bdw i am a new to android development. thanks

    • kahgoh says:

      Hi,

      I assume that you have created the project as an Android project in Eclipse and that you have also installed the Android plugin for Eclipse (if Build Automatically is set). The R class is generated and kept up to date for you by the Android plugins in Eclipse. First, you’ll need to make sure that you have defined the menu in a file called “menu.xml“, under the res/menu folder of your project. You might need to refresh your project to generate the R class or go to the Project menu and select Build Project. In the later versions, it is generated in the gen folder.

  16. Bill says:

    Is there a way to pass data back to the previous screen?

  17. Bill says:

    So, if the menu option displays an edit screen, then when that screen is closed, how do you pass the edited information back to the previous screen?

    • kahgoh says:

      You could try using a ContentProvider. The screen that edits the data then updates the data through the content provider and the activity that had the menu also uses the data from the ContentProvider.

      On a side note, I’ll be going on holidays for a few weeks. So if you have any more questions, I may not respond for a while and it may be faster to ask on StackOverflow.

  18. Kiran says:

    I need to add a menu with a single option to add a new button to my app( as an option ). Can you provide me the code for that?

    • kahgoh says:

      Hi,

      I already discussed how to create the menu here, so I assume you just need to know how to add the button dynamically. Adding the button is as simple as creating the button, setting its layout parameters and adding it to the layout. For example:

      public class SomeActivity extends Activity {
      
      	private static final int addButtonId = 100;
      
              // ...
      	
      	@Override
      	public boolean onCreateOptionsMenu(Menu menu) {
      		menu.add(0, addButtonId, 0, "Add Button");
      		return true;
      	}
      
      	@Override
      	public boolean onOptionsItemSelected(MenuItem item) {
      		if (item.getItemId() != addButtonId) {
      			return false;
      		}
      
      		// Assuming you want to add it to a linear layout with an
      		// id of "layout"
      		LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
      		Button button = new Button(this);
      		button.setText("A Button");
      		button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
      				LayoutParams.WRAP_CONTENT));
      		layout.addView(button);
      		return true;
      	}
      }
      
  19. bob says:

    Can you post a screenshot of what your menu looks like?

    Thanks.

  20. Linux says:

    Screenshots ?

Leave a comment